#!/usr/bin/env python

import argparse
import sys
import subprocess

ADDRESS= 'cri\\\\berald01@uk-cri-larc01.cri.camres.org' ## Note escaping \
BASEPATH= '/ArchiveDataFS2/Groups/sblab'

parser = argparse.ArgumentParser(description= """
DESCRIPTION
    Return the *last writable* directory from the cri archive server matching the pattern
    '20[1-2][0-9]-Q[1-4]', e.g. 2013-Q1.
    
""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('--address', '-a',
                   required= False,
                   default= ADDRESS,
                   help='''The address to the archive. Default "%s"
                   ''' %(ADDRESS))

parser.add_argument('--basepath', '-p',
                   required= False,
                   default= BASEPATH,
                   help='''The path to archive where the last writable dir is
to be found. Default "%s"
                   ''' %(BASEPATH))


def main():
    args = parser.parse_args()

    cmd= '''ssh %s "find %s -maxdepth 1 -type d -name '20[1-2][0-9]-Q[1-4]' -perm -u+w | sort" ''' %(args.address, args.basepath)
    p= subprocess.Popen(cmd, shell= True, stdout= subprocess.PIPE)
    p.wait()
    dirs= p.stdout.readlines()
    dirs= [x.strip() for x in dirs]
    if len(dirs) == 0:
        sys.exit('No writable directory found by:\n%s' %(cmd))
    print(dirs[-1])
    sys.exit()

if __name__ == '__main__':
    main()
